package openapi

import (
	"encoding/json"
	"os"
	"path/filepath"

	"github.com/getkin/kin-openapi/openapi3"
	"github.com/invopop/yaml"
)

func Save(def *openapi3.T, path string) error {
	bts, err := json.Marshal(def)
	if err == nil {
		bts, err = yaml.JSONToYAML(bts)
		if err == nil {
			var file *os.File

			_, err := os.Stat(path)

			if os.IsNotExist(err) {
				err = os.MkdirAll(filepath.Dir(path), 0600)
				if err == nil {
					if file, err = os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666); err == nil {
						_, err = file.Write(bts)
						if err == nil {
							file.Close()
						}
					}
				}
			}
			return err
		}
	}
	return err
}
